<template>
  <div style="position: relative" v-loading="isLoadingDefaultRoute" element-loading-text="加载中请稍后...">
    <div id="map-container" ref="mapContainer"></div>
    <div class="takeoff-point face-takeoff-point" v-if="isSetting_type == 1">
      点击地图设置起飞点
    </div>

    <section v-if="isSetting_type == 2">
      <div class="takeoff-point face-takeoff-point">点击地图进行绘制</div>
    </section>
    <div class="tips face-tips">
      <p>鼠标左键在绘制点双击结束绘制区域</p>
    </div>
    <div class="redtips" v-if="isPolygonFlag">
      <p>测区不支持交叉面，无法生成航线，请重新绘制</p>
    </div>
    <!-- 右边的功能 -->
    <linemap style="right: 20px !important" ref="mapviewRef" fromWhere="mapface" :rotation="rotation"
      :previousPitch="previousPitch" @viewClick="getviewClick" @mapsizeClick="getmapsizeClick"
      @viewcenterClick="getviewcenterClick" @clearClick="clearClick" @mapTypeClick="getmapTypeClick"
      @getsearchClick="getsearchClick" @selectItem="getselectItem"></linemap>
    <!-- <flaymap></flaymap> -->
  </div>
</template>
<script setup>
import {
  ref,
  watch,
  onMounted,
  onBeforeUnmount,
  defineProps,
  watchEffect,
  computed,
  onUnmounted,
  nextTick,
  toRef,
} from "vue";
import { useRoute } from "vue-router";
import AMapLoader from "@amap/amap-jsapi-loader";
import { ElIcon, ElInput, ElSelect, ElButton, ElMessage } from "element-plus";
import linemap from "./linemap2.vue";
import { getAirportListNoPage } from "#/api/sys/equipment";
import { generatorPlanarAirline } from "#/api/task/airline";
import RouteIcon from "./iocn.vue";
import { isPolygonSelfIntersecting, removeDuplicates } from "./mapdata2";
import "./mapdata2.css";
import { mapSetting } from "#/api/map";

// 必须在AMap JS加载前设置安全配置
window._AMapSecurityConfig = {
  securityJsCode: mapSetting.mapSecurity || "",
};
const mapviewRef = ref();
// const geocoder = ref(null); // 地理编码器实例
const tipInput = ref(""); // 检索关键字
const autoComplete = ref(null);
const placeSearch = ref(null);
const searchMarkers = ref([]);
const address = ref();
const point = ref([]);
const startMarker = ref({
  point: [], //坐标
}); //起飞点
const props = defineProps({
  flayShow: Boolean,
  flightaltitude: {
    type: Number,
    default: 300, // 默认海拔高度
  },
  drawDefaultRoute: {
    type: Array,
    default: () => [], // 默认航线数据
  },
  takeOffSecurityHeight: {
    type: Number,
    default: 300, // 默认起飞高度
  },
  airlineList: {
    type: Array,
    default: () => [], // 更新各个航点高度
  },
  coordinatePointReqList: {
    type: Array,
    default: () => [], // 默认航线数据
  },
  // takeOffRefPoint: {
  //   type: String,
  //   default: "", // 起飞点，格式："lng,lat,height"
  // },
  lineform: {
    type: String,
    default: {
      takeOffRefPoint: '',
      autoFlightSpeed: 0, //航线飞行速度
      direction: 0,//主航线角度
      height: 0,//主航线高度
      overlapH: 80, //航向重叠率
      overlapW: 70, //旁向重叠率
    },
  },
});
const emit = defineEmits(["gggallData", "area", "getstartMarker", "delSetTakeoffMode"]);
const lineform = toRef(props.lineform)
let lineform_x = JSON.parse(JSON.stringify(lineform.value))
// 获取路由参数
const route = useRoute();
const map = ref(null); // 地图实例
const loca = ref(null); // 实例
let polygonEditor;
let AMap = null; // 全局AMap引用
const mapContainer = ref(null); //地图绑定参数
const defaultCenter = [119.904953, 30.251849]; // 在组件顶部定义默认中心点
const isSetting_type = ref(3);//当前地图点击模式 1起飞点 2编辑区域 3无点击事件
const previousPitch = ref(50); // pitch值 地图视角倾斜角度
const map_loading = ref(true); // 地图是否已初始化完成
const airportList = ref([]); // 机场列表
const isLoadingDefaultRoute = ref(false); // 是否正在加载默认航线
// const offset = 0.00001; // 约1米偏移，确保线段可见
const satelliteLayer = ref(null); // 卫星图层
const roadNetLayer = ref(null); // 路网图层

const mouseTool = ref(null); // 鼠标工具
const isSettingTakeoff = ref(false); // 是否正在设置起飞点
const newLineWidth = ref(1); // 激光线宽度
const isPolygonFlag = ref(false); // 是否自相交
let takeoffMarker; //起飞点marker
//  默认数据
const allData = ref([]);
const lineData = ref([]);
const tempData = ref([]); // 暂存数据
// 初始化地图
const initMap = async () => {
  map_loading.value = true;
  await getAirportList();
  try {
    // 第一步：加载基础AMap
    AMap = await AMapLoader.load({
      key: mapSetting.mapKey,
      version: "2.0",
      plugins: [
        "AMap.PlaceSearch",
        "AMap.Geocoder",
        "AMap.AutoComplete",
        "AMap.Marker",
        "AMap.SetPitch",
        "AMap.Polygon",
        "AMap.MouseTool",
        "AMap.PolygonEditor",
      ],
      features: ["bg", "road"],
    });
    // 创建地图实例
    map.value = new AMap.Map(mapContainer.value, {
      resizeEnable: true, // 启用地图大小调整
      zoom: 18,
      center: defaultCenter, //默认中心点
      viewMode: "3D",
      pitch: previousPitch.value,
      rotateEnable: true, // 启用旋转
      dragEnable: true, // 启用拖拽
    });
    satelliteLayer.value = new AMap.TileLayer.Satellite();//卫星图
    roadNetLayer.value = new AMap.TileLayer.RoadNet();//路网
    //批量添加图层
    map.value.add([satelliteLayer.value, roadNetLayer.value]);
    if (!window.Loca) {
      await new Promise((resolve, reject) => {
        const script = document.createElement("script");
        script.src =
          "https://webapi.amap.com/loca?v=2.0&key=" + mapSetting.mapKey;
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    }
    // 2. 用 window.Loca 创建实例
    loca.value = new window.Loca.Container({ map: map.value });
    flayLine(loca.value);//初始化线条

    // 初始化地理编码器
    // if (AMap && AMap.Geocoder) {
    //   geocoder.value = new AMap.Geocoder({
    //     city: "010", //城市设为北京，默认："全国"
    //     radius: 1000, //范围，默认：500
    //   });
    // }
    // 搜索框自动完成类
    if (AMap && AMap.AutoComplete) {
      autoComplete.value = new AMap.AutoComplete({
        input: "keyword", // input 为绑定输入提示功能的input的DOM ID
      });
    }

    // 构造地点查询类
    if (AMap && AMap.PlaceSearch) {
      placeSearch.value = new AMap.PlaceSearch({
        map: map.value,
        autoFitView: false,
        map: null
      });
    }
    // 创建机场图标
    createCircleMarker();
    // 添加旋转事件监听
    initRotationListeners();
    // map添加点击事件
    if (map.value) {
      map.value.on("click", mapClick_f);
    };
    // 如果是新增模式（没有数据），自动进入设置起飞点模式
    if (allData.value.length === 0) {
      enterTakeoffMode();
    }
    // 地图初始化完成
    map_loading.value = false;
    // 如果输入框已经有值，初始化时触发一次搜索
    if (tipInput.value && placeSearch.value) {
      placeSearch.value.search(tipInput.value);
    }

  } catch (error) {
    console.error("地图初始化失败:", error);
  }
};
const rotation = ref(0);
// 监听地图视图变化
const initRotationListeners = () => {
  if (!map.value) return;
  // 监听地图视图变化
  map.value.on("viewchange", () => {
    rotation.value = map.value.getRotation() // 更新角度
    if (window.currentDeleteButton) {
      removeDeleteButton()
    }
    // previousPitch.value = map.value.getPitch(); // 更新Pitch值 用于右下角图标显示
    // set_map_for_pitch(pitch)
  });
};
// 地图点击事件
const mapClick_f = (e) => {
  if (!map.value) return;
  // if (!route.query.id) {
  // }
  if (isSetting_type.value == 1) {
    // 设置起飞点
    setStartMarker(e.lnglat);
  } else if (isSetting_type.value == 2) {
    // 设置面状区域
    mapClickHandler(e)
  }
}
const getAirportList = async () => {
  const params = {
    airportName: "",
    currentPage: "",
    pageSize: "",
  };
  const { data } = await getAirportListNoPage(params);
  if (data && data.length > 0) {
    airportList.value = data;
  } else {
    airportList.value = [];
  }
};
// 创建激光图层
const flayLine = (locaInstance) => {
  if (window.Loca && locaInstance) {
    try {
      // 创建 LineLayer（浮空线段）
      const lineLayer = new window.Loca.LineLayer({
        zIndex: 100, // 确保图层在上层
      });

      // 创建辅助线图层
      const guideLineLayer = new window.Loca.LaserLayer({
        zIndex: 55, // 确保辅助线在底层但可见
        zooms: [2, 20], //
      });

      // 设置 LineLayer 数据源
      lineLayer.setSource(
        new window.Loca.GeoJSONSource({
          data: {
            type: "FeatureCollection",
            features: [],
          },
        })
      );

      // 设置辅助线图层数据源
      guideLineLayer.setSource(
        new window.Loca.GeoJSONSource({
          data: {
            type: "FeatureCollection",
            features: [],
          },
        })
      );

      // 设置辅助线样式 - 使用静态线条
      guideLineLayer.setStyle({
        altitude: true, // 启用高度
        lineWidth: 3, // 线条宽度
        color: "#f0ed7a", // 黄色辅助线
      });

      // 设置 LineLayer 样式 浮空线段样式
      lineLayer.setStyle({
        altitude: true, // 启用高度
        lineWidth: 5, // 线段宽度
        color: "#00d58f", // 颜色属性名改为 color
      });

      // 将图层添加到loca容器
      locaInstance.add(lineLayer);
      locaInstance.add(guideLineLayer);

      // 保存图层引用到全局变量
      window.lineLayer = lineLayer;
      window.guideLineLayer = guideLineLayer;
      // 启动激光线动画
      if (locaInstance && locaInstance.animate) {
        locaInstance.animate.start();
      }
    } catch (error) {
      console.error("flayLine 创建图层时出错:", error);
    }
  }
};
// 创建机场图标
const createCircleMarker = () => {
  if (!map.value) {
    console.error("地图或图标图层未初始化，无法创建机场标记");
    return;
  }
  if (airportList.value.length > 0) {
    try {
      airportList.value.forEach((airport) => {
        const text = new AMap.Marker({
          position: [airport.longitude, airport.latitude],
          content: `<div class="airportstyle"><img src="/static/blueairport.png" width="40" height="40" style="display: block;" />
              <p style="margin: 2px 0 0 0; line-height: 1;">${airport.airportName}</p>
           </div>`,
          offset: new AMap.Pixel(-20, -30),
          zIndex: 0,
        });
        map.value.add(text);
      });

      // 设置地图中心点到第一个机场
      let center = [
        airportList.value[0].longitude,
        airportList.value[0].latitude,
      ];
      // map.value.setCenter(center);
      map.value.setFitView()
    } catch (error) {
      console.error("创建机场图标时出错:", error);
    }
  }
};
// 数据转换
const lnglatToNumber = (lng, lat) => {
  return [Number(lng.toFixed(12)), Number(lat.toFixed(12))];
};

// 创建封闭区域
const createPolygon = () => {
  if (!map.value) return;
  // 确保坐标数据格式正确
  console.log("allData.value", allData.value);
  // const pathData = converLngLat(allData.value);
  // 蓝色边框多边形
  const bluePolygon = new AMap.Polygon({
    map: map.value,
    path: allData.value,
    strokeColor: "#0066FF",
    strokeWeight: 5,
    strokeOpacity: 1,
    fillColor: "#0066FF",
    fillOpacity: 0.3,
    strokeStyle: "solid",
    zIndex: 10,
    bubble: true, // 启用拖动
  });
  // getArea();
  return { bluePolygon };
};

// 创建默认航线
const createDefaultRouteMarkers = (bluePolygon) => {
  if (!map.value) return;
  // 设置全局多边形引用
  window.currentPolygon = bluePolygon;
  // 检查绘制完成的多边形是否自相交
  if (isPolygonSelfIntersecting(AMap, allData.value)) {
    if (window.currentPolygon && window.currentPolygon.setOptions) {
      window.currentPolygon.setOptions({
        strokeColor: "#FF0000",
        fillColor: "#FF0000",
        fillOpacity: 0.3,
        strokeWeight: 5,
      });
    }
    isPolygonFlag.value = true;
  } else {
    isPolygonFlag.value = false;
    if (window.currentPolygon && window.currentPolygon.setOptions) {
      window.currentPolygon.setOptions({
        strokeColor: "#0066FF",
        fillColor: "#0066FF",
        fillOpacity: 0.2,
        strokeWeight: 5,
      });
    }
  }
  // 绘制完成后，添加点击事件监听器控制mark显示/隐藏
  addMarkVisibilityControl();

  // 阻止地图容器的默认右键菜单
  map.value.getContainer().addEventListener("contextmenu", (e) => {
    e.preventDefault();
  });

  // 如果已经存在右键事件监听器，先移除
  if (window.rightClickHandler) {
    map.value.off("rightclick", window.rightClickHandler);
  }
  // 保存右键事件处理函数引用
  window.rightClickHandler = rightClickHandler;

  // 添加地图右键事件，检测是否在面内部
  map.value.on("rightclick", rightClickHandler);
  showDefaultRouteMarkers(); //展示默认航线顶点
};
// 调整地图视图以显示整个航线
const adjustMapViewToRoute = () => {
  if (!map.value || !allData.value.length) return;
  try {
    // 计算航线的边界
    const coordinates = allData.value
      .map((coord) => {
        if (Array.isArray(coord)) {
          return { lng: coord[0], lat: coord[1] };
        } else if (
          coord &&
          typeof coord === "object" &&
          coord.lng !== undefined &&
          coord.lat !== undefined
        ) {
          return coord;
        }
        return null;
      })
      .filter((coord) => coord !== null);
    if (coordinates.length > 0) {
      const minLng = Math.min(...coordinates.map((p) => p.lng));
      const maxLng = Math.max(...coordinates.map((p) => p.lng));
      const minLat = Math.min(...coordinates.map((p) => p.lat));
      const maxLat = Math.max(...coordinates.map((p) => p.lat));
      // 创建边界对象
      const bounds = new AMap.Bounds([minLng, minLat], [maxLng, maxLat]);

      // 设置地图视图以包含整个航线，并添加一些边距
      map.value.setBounds(bounds, {
        padding: [50, 50, 50, 50], // 上下左右各添加50像素的边距
      });
    }
  } catch (error) {
    console.error("adjustMapViewToRoute - 设置地图边界时出错:", error);
  }
};

// 计算区域面积
const getArea = () => {
  if (allData.value.length > 0 && AMap) {
    try {
      // 确保坐标数据格式正确
      let pathData = allData.value;
      // 如果坐标数据是数组格式 [lng, lat]，需要转换为 AMap.LngLat 对象
      if (Array.isArray(allData.value[0])) {
        pathData = allData.value.map((coord) => {
          if (Array.isArray(coord) && coord.length >= 2) {
            return new AMap.LngLat(coord[0], coord[1]);
          }
          return coord;
        });
      }

      const area = Math.round(AMap.GeometryUtil.ringArea(pathData));
      emit("area", area);
    } catch (error) {
      console.error("计算区域面积时出错:", error);
    }
  }
};
let startPolygonDrawing;
// 绘制区域
const getmouseDrawClick = () => {// 绘制区域
  if (!map.value) return;

  // 清理之前的右键事件监听器
  // if (window.rightClickHandler && map.value) {
  //   map.value.off("rightclick", window.rightClickHandler);
  //   window.rightClickHandler = null;
  // }
  // 清理之前的删除按钮
  // if (window.currentDeletePolygonButton) {
  //   removeDeletePolygonButton();
  // }
  if (map.value) {
    map.value.setStatus({
      doubleClickZoom: false,
    });
  }
  if (allData.value.length == 0) {
    mouseTool.value = new AMap.MouseTool(map.value);
    polygonEditor = new AMap.PolygonEditor(map.value);
    const mapContainer = map.value.getContainer();
    mapContainer.style.cursor = "crosshair";
    // mouseTool.value.polygon({
    //   strokeColor: "#0066FF",
    //   strokeWeight: 5,
    //   strokeOpacity: 1,
    //   fillColor: "#0066FF",
    //   fillOpacity: 0.3,
    //   strokeStyle: "solid",
    //   zIndex: 10,
    //   bubble: true, // 启用拖动
    // });
    startPolygonDrawing = () => {
      mouseTool.value.polygon({
        strokeColor: "#0066FF",
        strokeWeight: 5,
        strokeOpacity: 1,
        fillColor: "#0066FF",
        fillOpacity: 0.3,
        strokeStyle: "solid",
        zIndex: 10,
        bubble: true, // 启用拖动
      });
    }
    startPolygonDrawing()
    //绘制完成
    mouseTool.value.on("draw", function (event) {
      const polygon = event.obj; // 获取刚绘制的多边形
      // const path = polygon.getPath(); // 获取当前路径（顶点数组）
      const path = removeDuplicates(polygon.getPath(), { precision: 6 })
      // console.log("draw", path)
      if (path.length < 3) {
        // 顶点少于3个，无效多边形
        // console.log("顶点不足3个，无法形成多边形，继续绘制");
        ElMessage({
          message: '顶点不足3个,无法生成航线，请重新绘制',
          type: 'warning',
        })
        allData.value = []
        if (window.markers && window.markers.length > 0) {
          map.value.remove(window.markers)
          window.markers = []
        }
        // 移除无效的多边形
        map.value.remove(polygon);
        // 不关闭 mouseTool，手动重新启动绘制
        startPolygonDrawing();
        return;
      }
      // console.log(path)
      showSegmentDistance(path);//用来更新绘制的圆点
      mouseTool.value.close(false); // true 表示清除临时覆盖物
      // console.log(mouseTool.value)
      allData.value = path.map(
        (point) => new AMap.LngLat(point.lng, point.lat)
      ); // 更新数据
      // 对allData.value进行去重
      allData.value = removeDuplicates(allData.value, {
        precision: 6,
      });
      // 检查绘制完成的多边形是否自相交
      if (isPolygonSelfIntersecting(AMap, allData.value)) {
        if (window.currentPolygon && window.currentPolygon.setOptions) {
          window.currentPolygon.setOptions({
            strokeColor: "#FF0000",
            fillColor: "#FF0000",
            fillOpacity: 0.3,
            strokeWeight: 5,
          });
        }
        isPolygonFlag.value = true;
        ElMessage({
          message: '绘制的区域错误,无法生成航线，请重新绘制',
          type: 'warning',
        })
        allData.value = []
        if (window.markers && window.markers.length > 0) {
          map.value.remove(window.markers)
          window.markers = []
        }
        if (window.distanceMarkers && window.distanceMarkers.length > 0) {
          window.distanceMarkers.forEach((marker) => {
            try {
              map.value.remove(marker);
            } catch (error) { }
          });
          window.distanceMarkers = [];
        }
        // 移除无效的多边形
        map.value.remove(polygon);
        cleanDuplicateMarkers();
        // 清理临时多边形
        if (window.tempPolygon) {
          try {
            map.value.remove(window.tempPolygon);
            window.tempPolygon = null;
          } catch (error) { }
        }
        if (window.distanceMarkers && window.distanceMarkers.length > 0) {
          window.distanceMarkers.forEach((marker) => {
            try {
              map.value.remove(marker);
            } catch (error) { }
          });
          window.distanceMarkers = [];
        }
        // 不关闭 mouseTool，手动重新启动绘制
        startPolygonDrawing();
        isPolygonFlag.value = false;
        return;
      } else {
        isPolygonFlag.value = false;
        if (window.currentPolygon && window.currentPolygon.setOptions) {
          window.currentPolygon.setOptions({
            strokeColor: "#0066FF",
            fillColor: "#0066FF",
            fillOpacity: 0.2,
            strokeWeight: 5,
          });
        }
      }
      isSetting_type.value = 3;
      mouseTool.value.close(false); // true 表示清除临时覆盖物
      map.value.setStatus({
        doubleClickZoom: true,
      });
      // mouseTool.value.close(); // 关闭绘制工具
      // 将所有坐标转换为AMap.LngLat对象数组
      // console.log("绘制结束allData.value", allData.value);
      get_online_line();//生成面状航线
      // 保存polygon引用，用于后续更新
      window.currentPolygon = event.obj;
      // 发送数据给父组件（转换为普通数组格式）
      // const normalData = allData.value.map((point) => [
      //   point.lng,
      //   point.lat,
      //   0,
      // ]);
      // emit("gggallData", normalData);
      // 绘制完成后，清理重复marker并移除地图点击事件监听
      cleanDuplicateMarkers();
      // 清理临时多边形
      if (window.tempPolygon) {
        try {
          map.value.remove(window.tempPolygon);
          window.tempPolygon = null;
        } catch (error) { }
      }

      // if (window.mapClickHandler) {
      //   map.value.off("click", window.mapClickHandler);
      //   window.mapClickHandler = null;
      // }
      // 关闭鼠标监听
      if (window.mouseDragHandler) {
        map.value.off("mousemove", window.mouseDragHandler);
        window.mouseDragHandler = null;
      }

      // 绘制完成后，添加点击事件监听器控制mark显示/隐藏
      addMarkVisibilityControl();

      // 阻止地图容器的默认右键菜单
      map.value.getContainer().addEventListener("contextmenu", (e) => {
        e.preventDefault();
      });

      // 如果已经存在右键事件监听器，先移除
      if (window.rightClickHandler) {
        map.value.off("rightclick", window.rightClickHandler);
      }
      // 保存右键事件处理函数引用
      window.rightClickHandler = rightClickHandler;

      // 添加地图右键事件，检测是否在面内部
      map.value.on("rightclick", rightClickHandler);
    });
    // 关闭鼠标监听
    if (window.mouseDragHandler) {
      map.value.off("mousemove", window.mouseDragHandler);
      window.mouseDragHandler = null;
    }
    //监听鼠标移动
    const mouseMoveHandler = (e) => mouseDragHandler(e);
    map.value.on("mousemove", mouseMoveHandler);
    window.mouseDragHandler = mouseMoveHandler; // 保存引用以便后续移除
    // 绑定地图点击事件
    // map.value.on("click", mapClickHandler);
    // 保存事件处理器引用，以便后续移除
    // window.mapClickHandler = mapClickHandler;
  }
};
// 监听地图点击事件
const mapClickHandler = async (event) => {
  // 检查是否正在绘制模式
  // console.log(mouseTool.value, isSetting_type.value)
  if (mouseTool.value && isSetting_type.value == 2) {
    // 确保window.markers已初始化
    if (!window.markers) {
      window.markers = [];
    } else {
      if (window.markers.length > 0 && window.markers[window.markers.length - 1]._position == [event.lnglat.lng, event.lnglat.lat]) {
        return;
      }
    }
    // console.log(mouseTool.value)
    // 创建标记
    const marker = new AMap.Marker({
      position: [event.lnglat.lng, event.lnglat.lat],
      content: `
          <div class="title-marker">
            <div class="tips-marker">
             <p> GPS:${event.lnglat.lng},${event.lnglat.lat}</p>
             <p>ASL:</p>
              </div>
             <div class="white-marker"></div>
            </div>
         `,
      offset: new AMap.Pixel(-8, -8),
      zIndex: 50,
      draggable: true,
      topWhenClick: true,
      extData: {
        index: window.markers.length
      }
    });
    map.value.add(marker);
    marker.on("dragging", (e) => dragHandler(e, marker)); //监听拖动
    marker.on("dragend", (e) => dragEndHandler(e, marker)); //监听拖动结束

    // 添加右键事件监听器
    marker.on("rightclick", (e) => {
      // 阻止默认右键菜单
      if (e.domEvent) {
        e.domEvent.preventDefault();
        e.domEvent.stopPropagation();
      }
      showDeleteButton(e, marker);
      return false;
    });

    // 阻止默认的右键菜单
    marker.on("contextmenu", (e) => {
      if (e.originalEvent) {
        e.originalEvent.preventDefault();
      }
      // 直接阻止默认行为
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      return false;
    });

    // 添加mousedown事件来阻止右键菜单
    marker.on("mousedown", (e) => {
      if (e.domEvent && e.domEvent.button === 2) {
        // 右键
        e.domEvent.preventDefault();
        e.domEvent.stopPropagation();
        return false;
      }
    });
    // 添加新marker
    window.markers.push(marker);
    // // 使用removeDuplicates函数去重
    // markers = removeDuplicates(markers, {
    //   precision: 6,
    //   onRemove: (duplicateMarker) => {
    //     // 移除重复的marker
    //     try {
    //       map.value.remove(duplicateMarker);
    //     } catch (error) { }
    //   },
    // });
    // console.log(window.markers)
  }
};

//默认数据展示顶点
const showDefaultRouteMarkers = (pathData) => {
  if (!map.value) return;
  const bluePolygon = new AMap.Polygon({
    map: map.value,
    path: allData.value,
    strokeColor: "#0066FF",
    strokeWeight: 5,
    strokeOpacity: 1,
    fillColor: "#0066FF",
    fillOpacity: 0.3,
    strokeStyle: "solid",
    zIndex: 10,
    bubble: true, // 启用拖动
  });
  // console.log(bluePolygon)
  const polygon = bluePolygon; // 获取刚绘制的多边形
  // const path = polygon.getPath(); // 获取当前路径（顶点数组）
  map.value.setStatus({
    doubleClickZoom: true,
  });
  isSetting_type.value = 3;
  get_online_line();
  window.currentPolygon = polygon;
  // 检查绘制完成的多边形是否自相交
  cleanDuplicateMarkers();
  // 清理临时多边形
  if (window.tempPolygon) {
    try {
      map.value.remove(window.tempPolygon);
      window.tempPolygon = null;
    } catch (error) { }
  }
  // 关闭鼠标监听
  if (window.mouseDragHandler) {
    map.value.off("mousemove", window.mouseDragHandler);
    window.mouseDragHandler = null;
  }

  // 绘制完成后，添加点击事件监听器控制mark显示/隐藏
  addMarkVisibilityControl();

  // 阻止地图容器的默认右键菜单
  map.value.getContainer().addEventListener("contextmenu", (e) => {
    e.preventDefault();
  });
  // 如果已经存在右键事件监听器，先移除
  if (window.rightClickHandler) {
    map.value.off("rightclick", window.rightClickHandler);
  }
  // 保存右键事件处理函数引用
  window.rightClickHandler = rightClickHandler;

  // 添加地图右键事件，检测是否在面内部
  map.value.on("rightclick", rightClickHandler);

  allData.value.forEach((coord, index) => {
    const position = [coord.lng, coord.lat];
    const marker = new AMap.Marker({
      position: position,
      content: `
          <div class="title-marker">
            <div class="tips-marker">
             <p> GPS:${position[0]},${position[1]}</p>
             <p>ASL:</p>
              </div>
             <div class="white-marker"></div>
            </div>
         `,
      offset: new AMap.Pixel(-8, -8),
      zIndex: 50,
      draggable: true,
      topWhenClick: true,
      extData: {
        index
      }
    });
    map.value.add(marker);
    marker.on("dragging", (e) => dragHandler(e, marker)); //监听拖动
    marker.on("dragend", (e) => dragEndHandler(e, marker)); //监听拖动结束

    // 添加右键事件监听器
    marker.on("rightclick", (e) => {
      // 阻止默认右键菜单
      if (e.domEvent) {
        e.domEvent.preventDefault();
        e.domEvent.stopPropagation();
      }
      showDeleteButton(e, marker);
      return false;
    });

    // 阻止默认的右键菜单
    marker.on("contextmenu", (e) => {
      if (e.originalEvent) {
        e.originalEvent.preventDefault();
      }
      // 直接阻止默认行为
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      return false;
    });

    // 添加mousedown事件来阻止右键菜单
    marker.on("mousedown", (e) => {
      if (e.domEvent && e.domEvent.button === 2) {
        // 右键
        e.domEvent.preventDefault();
        e.domEvent.stopPropagation();
        return false;
      }
    });
    // 确保window.markers已初始化
    if (!window.markers) {
      window.markers = [];
    }
    // 添加新marker
    window.markers.push(marker);
    showSegmentDistance(allData.value);
  });
};
// 创建右键事件处理函数
const rightClickHandler = (e) => {
  // 检查是否有绘制的多边形
  // if (allData.value && allData.value.length > 2) {
  //   const clickPoint = e.lnglat;

  //   // 检查点击点是否在多边形内部
  //   const isInside = AMap.GeometryUtil.isPointInPolygon(
  //     clickPoint,
  //     allData.value
  //   );

  //   if (isInside) {
  //     // 在面内部右键，显示删除整个面的按钮
  //     showDeletePolygonButton(e, clickPoint);
  //   }
  // }
};

//监听鼠标拖动
const mouseDragHandler = (e) => {
  let dragingPoint = new AMap.LngLat(e.lnglat.lng, e.lnglat.lat);

  if (!window.markers) return;
  // 获取所有marker位置并检查自相交
  let markers = window.markers.map((m) => m.getPosition());
  markers.push(dragingPoint);
  if (mouseTool.value && markers.length > 2) {
    // 检查是否自相交
    if (isPolygonSelfIntersecting(AMap, markers)) {
      isPolygonFlag.value = true;
      // 移除之前的临时多边形
      if (window.tempPolygon) {
        try {
          map.value.remove(window.tempPolygon);
        } catch (error) { }
        window.tempPolygon = null;
      }

      // 创建红色临时多边形
      window.tempPolygon = new AMap.Polygon({
        map: map.value,
        path: markers,
        strokeColor: "#FF0000", // 红色边框
        strokeWeight: 5,
        strokeOpacity: 1,
        fillColor: "#FF0000", // 红色填充
        fillOpacity: 0.3,
        strokeStyle: "solid",
        zIndex: 10,
      });
    } else {
      isPolygonFlag.value = false;

      // 移除临时多边形
      if (window.tempPolygon) {
        try {
          map.value.remove(window.tempPolygon);
          window.tempPolygon = null;
        } catch (error) { }
      }
    }

    // 显示线段距离和中间点
    // console.log(456654)
    showSegmentDistance(markers);
  }
};

//监听鼠标按下空心小圆点
const mousedownHandler = (e, marker) => {
  console.log('按下空心小圆点')
  // console.log(e, marker)
  // 获取空心小圆点的位置
  let point = new AMap.LngLat(e.lnglat.lng, e.lnglat.lat);

  // 找到空心小圆点对应的线段索引
  let segmentIndex = e.target.getExtData().index || -1;
  let isLastSegment = false;
  const ms = e.target.getExtData();
  // console.log(window.markers)
  // 遍历所有线段，找到对应的空心小圆点
  // console.log(e.target.getExtData())
  for (let i in window.markers) {
    // const start = window.markers[i].getPosition();
    // const end = window.markers[i + 1].getPosition();
    // const midLng = (start.lng + end.lng) / 2;
    // const midLat = (start.lat + end.lat) / 2;

    // // 检查是否是当前空心小圆点
    // if (
    //   Math.abs(midLng - point.lng) < 0.0001 &&
    //   Math.abs(midLat - point.lat) < 0.0001
    // ) {
    //   segmentIndex = i;
    //   break;
    // }
    // console.log(window.markers[i])
    let m = window.markers[i].getExtData()
    if (m.index == ms.i) {
      segmentIndex = i;
      if (segmentIndex == window.markers.length - 1) {
        isLastSegment = true
      }
      break;
    }
  }
  // 检查是否是最后一个线段（从最后一个点到第一个点）
  // if (segmentIndex === -1 && window.markers.length > 2) {
  //   const start = window.markers[window.markers.length - 1].getPosition();
  //   const end = window.markers[0].getPosition();
  //   const midLng = (start.lng + end.lng) / 2;
  //   const midLat = (start.lat + end.lat) / 2;

  //   if (
  //     Math.abs(midLng - point.lng) < 0.0001 &&
  //     Math.abs(midLat - point.lat) < 0.0001
  //   ) {
  //     segmentIndex = window.markers.length - 1;
  //     isLastSegment = true;
  //   }
  // }

  if (segmentIndex !== -1) {
    // 在对应位置插入新顶点
    let insertIndex;
    if (isLastSegment) {
      insertIndex = allData.value.length;
    } else {
      insertIndex = Number(segmentIndex) + 1;
    }
    // 在allData中插入新顶点
    allData.value.splice(insertIndex, 0, point);
    // 创建新的顶点标记
    const newVertexMarker = new AMap.Marker({
      position: point,
      content: `
          <div class="title-marker">
            <div class="tips-marker">
             <p> GPS:${point.lng},${point.lat}</p>
             <p>ASL:</p>
              </div>
             <div class="white-marker"></div>
           </div>
        `,
      offset: new AMap.Pixel(-8, -8),
      zIndex: 50,
      draggable: true,
      topWhenClick: true,
      extData: {
        index: insertIndex
      }
    });
    // console.log(newVertexMarker)
    // 绑定拖动事件
    newVertexMarker.on("dragging", (e) => dragHandler(e, newVertexMarker));
    newVertexMarker.on("dragend", (e) => dragEndHandler(e, newVertexMarker));
    // 添加右键事件监听器
    newVertexMarker.on("rightclick", (e) => {
      // 阻止默认右键菜单
      if (e.domEvent) {
        e.domEvent.preventDefault();
        e.domEvent.stopPropagation();
      }
      showDeleteButton(e, newVertexMarker);
      return false;
    });

    // 阻止默认的右键菜单
    newVertexMarker.on("contextmenu", (e) => {
      if (e.originalEvent) {
        e.originalEvent.preventDefault();
      }
      // 直接阻止默认行为
      e.preventDefault && e.preventDefault();
      e.stopPropagation && e.stopPropagation();
      return false;
    });

    // 添加mousedown事件来阻止右键菜单
    newVertexMarker.on("mousedown", (e) => {
      if (e.domEvent && e.domEvent.button === 2) {
        // 右键
        e.domEvent.preventDefault();
        e.domEvent.stopPropagation();
        return false;
      }
    });

    // 添加到地图
    map.value.add(newVertexMarker);
    // 添加到markers数组
    window.markers.splice(insertIndex, 0, newVertexMarker);
    reset_markers_index()

    // 更新多边形路径
    if (window.currentPolygon) {
      window.currentPolygon.setPath(allData.value);

      // 检查是否自相交
      if (isPolygonSelfIntersecting(AMap, allData.value)) {
        window.currentPolygon.setOptions({
          strokeColor: "#FF0000",
          fillColor: "#FF0000",
          fillOpacity: 0.3,
          strokeWeight: 5,
        });
        isPolygonFlag.value = true;
      } else {
        window.currentPolygon.setOptions({
          strokeColor: "#0066FF",
          fillColor: "#0066FF",
          fillOpacity: 0.2,
          strokeWeight: 5,
        });
        isPolygonFlag.value = false;
      }
    }

    // 重新显示线段距离和中间点（因为线段数量变了）
    showSegmentDistance(allData.value);

    // 发送数据给父组件
    const normalData = allData.value.map((point) => [point.lng, point.lat]);
    // emit("allData", normalData);
  }
};
const reset_markers_index = () => {
  for (let i in window.markers) {
    let data = window.markers[i].getExtData();
    data.index = i;
    window.markers[i].setExtData(data);
  }
}
//监听marker拖动
const dragHandler = (e, marker) => {
  // if (mouseTool.value) {
  // console.log("监听marker拖动");
  const newPosition = e.lnglat;
  // 更新allData.value中的对应点
  // console.log(allData.value);
  if (allData.value && allData.value.length > 0) {
    // 找到当前marker对应的索引
    const markerIndex = findMarkerIndex(marker);
    if (markerIndex !== -1) {
      // 直接更新为AMap.LngLat对象
      allData.value[markerIndex] = newPosition;

      // 更新marker的显示内容（GPS坐标）
      const newContent = `
              <div class="title-marker">
                <div class="tips-marker">
                 <p> GPS:${newPosition.lng.toFixed(
        6
      )},${newPosition.lat.toFixed(6)}</p>
                 <p>ASL: 275.8m</p>
                  </div>
                 <div class="white-marker"></div>
               </div>
            `;
      marker.setContent(newContent);

      // 清理重复的allData
      // cleanDuplicateAllData();
      // 更新多边形路径
      if (window.currentPolygon) {
        window.currentPolygon.setPath(allData.value);
        // 检查是否自相交
        if (isPolygonSelfIntersecting(AMap, allData.value)) {
          //更新绘制的区域为红色边框和红色填充
          window.currentPolygon.setOptions({
            strokeColor: "#FF0000", // 新边框颜色，如 "#FF0000"
            fillColor: "#FF0000", // 新填充颜色，如 "#00FF00"
          });
        } else {
          window.currentPolygon.setOptions({
            strokeColor: "#0066FF", // 新边框颜色，如 "#FF0000"
            fillColor: "#0066FF", // 新填充颜色，如 "#00FF00"
          });
        }
      }
      // 更新距离标记位置
      showSegmentDistance(allData.value);
    }
  }
  if (window.currentDeleteButton) {
    removeDeleteButton()
  }
  // }
};

//监听marker拖动结束
const dragEndHandler = (e, marker) => {
  // if (mouseTool.value) {
  // 监听拖动结束事件
  const finalPosition = e.lnglat;
  if (allData.value && allData.value.length > 0) {
    // 找到当前marker对应的索引
    const markerIndex = findMarkerIndex(marker);
    if (markerIndex !== -1) {
      // 直接更新为AMap.LngLat对象
      allData.value[markerIndex] = finalPosition;
      // 清理重复的allData
      // cleanDuplicateAllData();
      // 更新多边形路径
      if (window.currentPolygon) {
        window.currentPolygon.setPath(allData.value);
        // 检查是否自相交
        if (isPolygonSelfIntersecting(AMap, allData.value)) {
          isPolygonFlag.value = true;
          // ElMessage.error("绘制的区域自相交，请重新绘制");
          return;
        } else {
          isPolygonFlag.value = false;
        }
      }
      // 更新距离标记位置
      showSegmentDistance(allData.value);
      // 发送最终数据给父组件（转换为普通数组格式）
      const normalData = allData.value.map((point) => [
        point.lng,
        point.lat,
        0,
      ]);
      // getArea(); //计算面积
      // emit("gggallData", normalData);
      get_online_line();//生成面状航线
    }
  }
  // }
};
let flightPath_data = {};
// 获取航线 获取面状航线 生成航线 生成面状航线 创建航线
const get_online_line = async () => {
  // console.log(allData.value)
  //   "longitude": 119.906292,
  // "latitude": 30.254898,
  // "height": 0
  //   lat
  // lng
  // lineform
  if (allData.value.length < 3) return;
  let coordinatePointReqList = [];
  for (let i of allData.value) {
    coordinatePointReqList.push({
      longitude: i.lng,
      latitude: i.lat,
      height: lineform.value.height,
    })
  }
  let params = {
    speed: lineform.value.autoFlightSpeed,
    height: lineform.value.height,
    direction: lineform.value.direction,
    overlapW: lineform.value.overlapW,
    overlapH: lineform.value.overlapH,
    coordinatePointReqList
  }
  const { code, msg, data } = await generatorPlanarAirline(params);
  if (code != 200) {
    ElMessage({
      message: msg,
      type: 'warning',
    })
    return;
  }
  emit("area", {
    coverageArea: data.coverageArea,
    totalDistance: data.totalDistance,
    estimatedFlightTime: data.estimatedFlightTime,
    estimatedPhotoCount: data.estimatedPhotoCount,
  });
  if (data.flightPath.length === 0) {
    ElMessage({
      message: '所划区域无法生成航线',
      type: 'warning',
    })
  }
  flightPath_data = data
  set_airline()
}
const set_airline = () => {
  const waypoints = flightPath_data?.flightPath || [];
  let coordinatePointReqList = [];
  let arr = []
  // 生成线数据
  if (waypoints.length == 0) {
    window.lineLayer.setSource(new Loca.GeoJSONSource({
      data: {
        type: 'FeatureCollection',
        features: arr,
      },
    }));
    window.lineLayer.render();
    for (let i of allData.value) {
      coordinatePointReqList.push({
        longitude: i.lng,
        latitude: i.lat,
        height: lineform.value.height,
      })
    }
    emit("gggallData", {
      coordinatePointReqList,
      waypoints,
    });
    return
  };
  for (let i = 0; i < waypoints.length - 1; i++) {
    arr.push({
      type: 'Feature',
      geometry: {
        type: 'LineString',
        coordinates: [
          [waypoints[i].longitude, waypoints[i].latitude, lineform.value.height],
          [waypoints[i + 1].longitude, waypoints[i + 1].latitude, lineform.value.height]
        ]
      }
    });
  }
  arr.push({
    type: 'Feature',
    geometry: {
      type: 'LineString',
      coordinates: [
        [waypoints[0].longitude, waypoints[0].latitude, lineform.value.height],
        [startMarker.value.point[0], startMarker.value.point[1], lineform.value.takeOffSecurityHeight],
      ]
    }
  });
  lineData.value = arr;
  // 添加标记点
  // waypoints.forEach((point, index) => {
  //   const marker = new AMap.Marker({
  //     position: [point.longitude, point.latitude],
  //     offset: new AMap.Pixel(-10, -10),
  //     content: `<div style="background-color: red; color: white; padding: 2px 6px; border-radius: 3px; font-size: 12px; user-select: none;">${index + 1}</div>`,
  //     zIndex: 101,
  //     extData: {
  //       altitude: point.height,
  //     }
  //   });
  //   map.add(marker);
  //   render_marker_height(marker);
  //   markers.push(marker);
  // });

  // 渲染线图层
  if (window.lineLayer) {
    window.lineLayer.setSource(new Loca.GeoJSONSource({
      data: {
        type: 'FeatureCollection',
        features: arr,
      },
    }));
    window.lineLayer.render();
  }

  // 调整地图视角以适应所有标记点
  // map.value.setFitView(markers);

  for (let i of allData.value) {
    coordinatePointReqList.push({
      longitude: i.lng,
      latitude: i.lat,
      height: lineform.value.height,
    })
  }
  emit("gggallData", {
    coordinatePointReqList,
    waypoints,
    // startprint: startMarker.value.point,
  });
}
// 清理重复的marker
const cleanDuplicateMarkers = () => {
  if (!window.markers || window.markers.length === 0) return;
  const uniqueMarkers = removeDuplicates(window.markers, {
    precision: 6,
    onRemove: (marker) => {
      // 移除重复的marker
      try {
        map.value.remove(marker);
      } catch (error) { }
    },
  });

  window.markers = uniqueMarkers;
};

// 清理重复的allData
const cleanDuplicateAllData = () => {
  if (!allData.value || allData.value.length === 0) return;
  const uniqueData = removeDuplicates(allData.value, {
    precision: 6,
    onRemove: (point) => { },
  });
  allData.value = uniqueData;
};

// 显示删除按钮
const showDeleteButton = (e, marker) => {
  // 阻止默认右键菜单 - 高德地图事件对象结构不同
  if (window.currentDeleteButton) {
    removeDeleteButton()
  }
  if (e.domEvent && e.domEvent.preventDefault) {
    e.domEvent.preventDefault();
    e.domEvent.stopPropagation();
  }

  // 阻止事件冒泡
  if (e.preventDefault) {
    e.preventDefault();
  }
  if (e.stopPropagation) {
    e.stopPropagation();
  }

  // 检查是否至少保留3个顶点（三角形）
  if (window.markers.length <= 3) {
    ElMessage.warning("至少需要保留3个顶点");
    return;
  }

  // 获取marker位置
  const position = marker.getPosition();
  const pixel = map.value.lngLatToContainer(position);

  // 创建删除按钮
  const deleteButton = document.createElement("div");
  deleteButton.className = "delete-button-container";
  deleteButton.innerHTML = `
        <div class="delete-tips-marker">
          <p class="delete-confirm-btn">删除端点</p>
        </div>
      `;

  // 设置删除按钮位置
  deleteButton.style.position = "absolute";
  deleteButton.style.left = pixel.x + 10 + "px";
  deleteButton.style.top = pixel.y - 10 + "px";
  deleteButton.style.zIndex = "1000";

  // 添加到地图容器
  map.value.getContainer().appendChild(deleteButton);

  // 绑定删除按钮事件
  deleteButton.addEventListener("click", () => {
    deleteVertex(marker);
    removeDeleteButton();
  });
  // 保存删除按钮引用，用于后续移除
  window.currentDeleteButton = deleteButton;

  // 添加点击其他地方关闭删除按钮的事件
  setTimeout(() => {
    // 监听地图点击事件
    map.value.on("click", () => {
      removeDeleteButton();
    });

    // 监听文档点击事件
    document.addEventListener("click", closeDeleteButtonOnOutsideClick);
  }, 100);

  // 返回false阻止默认行为
  return false;
};

// 移除删除按钮
const removeDeleteButton = () => {
  if (window.currentDeleteButton) {
    window.currentDeleteButton.remove();
    window.currentDeleteButton = null;
  }
  // 移除点击其他地方关闭的事件监听器
  document.removeEventListener("click", closeDeleteButtonOnOutsideClick);
};

// 点击其他地方关闭删除按钮
const closeDeleteButtonOnOutsideClick = (e) => {
  if (
    window.currentDeleteButton &&
    !window.currentDeleteButton.contains(e.target)
  ) {
    removeDeleteButton();
  }
};

// 查找marker对应的索引
const findMarkerIndex = (targetMarker) => {
  if (!window.markers) return -1;

  for (let i = 0; i < window.markers.length; i++) {
    if (window.markers[i] === targetMarker) {
      return i;
    }
  }
  return -1;
};
// 删除顶点
const deleteVertex = (marker) => {
  try {
    // 找到marker对应的索引
    const markerIndex = findMarkerIndex(marker);
    if (markerIndex === -1) {
      console.error("未找到要删除的marker");
      return;
    }

    // 从地图中移除marker
    map.value.remove(marker);

    // 从markers数组中移除
    window.markers.splice(markerIndex, 1);
    reset_markers_index()
    // 从allData中移除对应的坐标点
    allData.value.splice(markerIndex, 1);

    // 更新多边形路径
    if (window.currentPolygon) {
      window.currentPolygon.setPath(allData.value);

      // 检查是否自相交
      if (isPolygonSelfIntersecting(AMap, allData.value)) {
        window.currentPolygon.setOptions({
          strokeColor: "#FF0000",
          fillColor: "#FF0000",
          fillOpacity: 0.3,
          strokeWeight: 5,
        });
        isPolygonFlag.value = true;
      } else {
        window.currentPolygon.setOptions({
          strokeColor: "#0066FF",
          fillColor: "#0066FF",
          fillOpacity: 0.2,
          strokeWeight: 5,
        });
        isPolygonFlag.value = false;
      }
    }

    // 重新显示线段距离和中间点
    showSegmentDistance(allData.value);

    // 计算面积
    // getArea();
    ElMessage.success("顶点删除成功");
    get_online_line();//生成面状航线
  } catch (error) {
    console.error("删除顶点时出错:", error);
    ElMessage.error("删除顶点失败");
  }
};
// 生成唯一id
const generateUniqueId = () => {
  const timestamp = Date.now().toString(36);
  const random = Math.random().toString(36).substring(2);
  return timestamp + random;
}
// 显示线段距离和中间点
const showSegmentDistance = (markers) => {
  // console.log("显示线段距离和中间点showSegmentDistance", markers);
  // 清理之前的距离标记
  if (window.distanceMarkers) {
    window.distanceMarkers.forEach((marker) => {
      try {
        map.value.remove(marker);
      } catch (error) { }
    });
    window.distanceMarkers = [];
  }
  // console.log(markers)
  // 为每个线段创建距离标记
  for (let i = 0; i < markers.length - 1; i++) {
    const start = markers[i];
    const end = markers[i + 1];

    // 计算线段中点
    const midLng = (start.lng + end.lng) / 2;
    const midLat = (start.lat + end.lat) / 2;
    const midPoint = new AMap.LngLat(midLng, midLat);

    // 计算距离（米）
    const distance = AMap.GeometryUtil.distance(start, end);
    const distanceText = distance.toFixed(1) + " m";
    // 创建空心圆点
    const circleMarker = new AMap.Marker({
      position: midPoint,
      content: `<div style="
            width: 12px;
            height: 12px;
            border: 2px solid white;
            border-radius: 50%;
            background:rgba(255, 255, 255, 0.5);
            box-shadow: 0 0 4px rgba(0,0,0,0.5);
          "></div>`,
      offset: new AMap.Pixel(-6, -6),
      topWhenClick: true,
      draggable: true,
      extData: {
        i,
      }
    });
    circleMarker.on("mousedown", (e) => mousedownHandler(e, circleMarker)); //监听鼠标按下
    circleMarker.on("dragging", (e) => dragHandler(e, circleMarker)); //监听拖动
    circleMarker.on("dragend", (e) => dragEndHandler(e, circleMarker)); //监听拖动结束
    // 创建距离标签
    const distanceLabel = new AMap.Marker({
      position: midPoint,
      content: `<div style="
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
            white-space: nowrap;
            box-shadow: 0 1px 3px rgba(0,0,0,0.3);
          ">${distanceText}</div>`,
      offset: new AMap.Pixel(-20, -25),
      zIndex: 16,
    });

    map.value.add(circleMarker);
    map.value.add(distanceLabel);

    // 保存标记引用
    if (!window.distanceMarkers) {
      window.distanceMarkers = [];
    }
    window.distanceMarkers.push(circleMarker, distanceLabel);
  }

  // 处理最后一个线段（从最后一个点到第一个点）
  if (markers.length > 2) {
    const start = markers[markers.length - 1];
    const end = markers[0];

    // 计算线段中点
    const midLng = (start.lng + end.lng) / 2;
    const midLat = (start.lat + end.lat) / 2;
    const midPoint = new AMap.LngLat(midLng, midLat);

    // 计算距离（米）
    const distance = AMap.GeometryUtil.distance(start, end);
    const distanceText = distance.toFixed(1) + " m";
    // console.log("distanceText", distanceText);
    // 创建空心圆点
    const circleMarker = new AMap.Marker({
      position: midPoint,
      content: `<div style="
            width: 12px;
            height: 12px;
            border: 2px solid white;
            border-radius: 50%;
            background:rgba(255, 255, 255, 0.5);
            box-shadow: 0 0 4px rgba(0,0,0,0.5);
          "></div>`,
      offset: new AMap.Pixel(-6, -6),
      zIndex: 15,
      extData: {
        i: markers.length - 1,
      }
    });
    circleMarker.on("mousedown", (e) => mousedownHandler(e, circleMarker)); //监听鼠标按下
    circleMarker.on("dragging", (e) => dragHandler(e, circleMarker)); //监听拖动
    circleMarker.on("dragend", (e) => dragEndHandler(e, circleMarker)); //监听拖动结束
    // 创建距离标签
    const distanceLabel = new AMap.Marker({
      position: midPoint,
      content: `<div style="
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 12px;
            white-space: nowrap;
            box-shadow: 0 1px 3px rgba(0,0,0,0.3);
          ">${distanceText}</div>`,
      offset: new AMap.Pixel(-20, -25),
      zIndex: 16,
    });

    map.value.add(circleMarker);
    map.value.add(distanceLabel);

    // 保存标记引用
    if (!window.distanceMarkers) {
      window.distanceMarkers = [];
    }
    window.distanceMarkers.push(circleMarker, distanceLabel);
  }
  // console.log(1111, window.distanceMarkers)
};
// 绑定地图点击事件
const bindMapClickEvent = () => {
  if (!map.value) return;
  // 监听地图缩放事件  修改激光线粗细
  // map.value.on("zoomend", (e) => {
  //   if (!startMarker.value.point) return;
  //   const zoom = map.value.getZoom();
  //   if (zoom >= 18) {
  //     newLineWidth.value = 1;
  //   } else if (zoom >= 15) {
  //     newLineWidth.value = 3;
  //   } else {
  //     newLineWidth.value = 5;
  //   }
  //   console.log("zoom", zoom, newLineWidth.value);
  //   setLaserLine(startMarker.value.point);
  // });
};
// 进入起飞点设置模式
const enterTakeoffMode = () => {
  // 设置光标为十字，类似图片中的效果
  if (map.value) {
    const mapContainer = map.value.getContainer();
    mapContainer.style.cursor = "crosshair";
  }
  isSetting_type.value = 1;
  // console.log("进入起飞点设置模式，点击地图设置起飞点");
};
// 起飞点设置结束
const exitTakeoffMode = () => {
  if (allData.value.length == 0) {  // 如果绘制区域为空
    getmouseDrawClick(); // 区域绘制
    isSetting_type.value = 2;
  } else {
    isSetting_type.value = 3;
    // 恢复默认光标
    if (map.value) {
      map.value.getContainer().style.cursor = "default";
    }
  }
};
//设置起飞点
const setStartMarker = (option, isnext = true) => {
  if (!map.value) return;
  if (takeoffMarker) map.value.remove(takeoffMarker);
  takeoffMarker = new AMap.Marker({
    position: [option.lng, option.lat],
    content: `<div style="display:flex;align-items:center;justify-content:center;width:30px;height:30px;font-weight:bold;color:white;background:#fff;border-radius:50%;"><img src="/static/flay.png" width="24" height="24" /></div>`,
    offset: new AMap.Pixel(-13, -20),
    extData: {
      altitude: 0, // 起飞点标记保持在地面
      index: -1,
      originalPosition: [option.lng, option.lat],
    },
    draggable: true, // 允许起飞点拖动
  });
  // 添加拖动过程中的实时更新
  takeoffMarker.on("dragging", (e) => {
    const newPosition = e.lnglat;
    // 实时更新激光线位置
    startMarker.value.point = [newPosition.lng, newPosition.lat];
    emit("getstartMarker", startMarker.value.point);
    setLaserLine();
  });

  // 添加拖动结束事件监听
  takeoffMarker.on("dragend", (e) => {
    const newPosition = e.lnglat;
    // 更新起飞点位置
    startMarker.value.point = [newPosition.lng, newPosition.lat];
    // 拖动结束后向父组件传递新的起飞点位置
    emit("getstartMarker", startMarker.value.point);
    // 更新激光线位置
    setLaserLine();
  });
  map.value.add(takeoffMarker);
  startMarker.value.point = [option.lng, option.lat];
  emit("getstartMarker", startMarker.value.point);
  setLaserLine(); //设置激光线
  // 起飞点设置结束
  if (isnext) {
    exitTakeoffMode()
  }
};
// 重设起飞点
const enterSetTakeoffMode = () => {
  // map.value.getContainer().style.cursor = "crosshair"; // 设置鼠标样式
  // 禁用双击放大功能，防止在设置起飞点时意外放大地图
  if (map.value) {
    map.value.setStatus({
      doubleClickZoom: false,
    });
    // 进入起飞点设置模式
    if (allData.value.length < 3) {
      allData.value = []
      if (window.markers && window.markers.length > 0) {
        map.value.remove(window.markers)
        window.markers = []
      }
      // 移除无效的多边形
      mouseTool.value.close(true)
    }
    enterTakeoffMode();
  }
};
// 退出"设置起飞点"模式
const exitSetTakeoffMode = () => {
  // 只有在非重设模式下才发送事件（避免重复发送）
  // exitTakeoffMode()
  // 恢复双击放大功能
  if (map.value) {
    map.value.setStatus({
      doubleClickZoom: true,
    });
  }
  map.value.getContainer().style.cursor = "default"; // 恢复鼠标样式
  exitTakeoffMode()
  // 移除地图点击事件监听器
  // if (map.value && window.mapClickHandler) {
  //   map.value.off("click", window.mapClickHandler);
  //   window.mapClickHandler = null;
  // }
  // map.value.on("click", takeoffClickHandler);
  // map.value.off("click", handleMapClickForTakeoff); // 移除地图点击监听
};
//设置激光线 - 使用专门的激光图层
const setLaserLine = (option) => {
  if (!map.value) return;
  // console.log(lineform.value.height, window.guideLineLayer)
  if (window.guideLineLayer) {
    window.guideLineLayer.setSource(
      new window.Loca.GeoJSONSource({
        data: {
          type: "FeatureCollection",
          features: [
            {
              geometry: {
                coordinates: startMarker.value.point,
                type: "Point",
              },
              type: "Feature",
              properties: {
                h: lineform.value.takeOffSecurityHeight,
              },
            },
          ],
        },
      }),
      {
        unit: "meter",
        height: (index, feature) => {
          const height = feature.properties.h; // 使用高度因子，
          return height;
        },
        // height: lineform.value.hight,
        color: "#00d58f", // 绿色激光线
        lineWidth: 2, // 适中的线条宽度，确保可见
        trailLength: 50000,
        repeat: 0,
      }
    );
    // window.guideLineLayer.render();
    if (flightPath_data?.flightPath && flightPath_data?.flightPath.length > 0) {
      set_airline()
    }
  }
};
// 回到地图中心点
const getviewcenterClick = () => {
  map.value.setCenter(defaultCenter);
};
// 获取地图视角 2d 3d
const getviewClick = (value, pitch) => {
  map.value.setPitch(value ? (pitch ? pitch : 50) : 0);
  if (!value) {
    previousPitch.value = 0;
  }
};
// 获取地图尺寸
const getmapsizeClick = (operation) => {
  if (map.value) {
    let currentZoom = map.value.getZoom(); // 获取当前地图缩放级别
    const zoomChange = operation === "add" ? 0.1 : -0.1; // 每次点击缩放变化量，可根据需要调整
    map.value.setZoomAndCenter(currentZoom + zoomChange, map.value.getCenter()); // 设置新的缩放级别，同时保持当前地图中心不变
  }
};
// 检查图层是否存在的辅助函数
const hasLayer = (className) => {
  if (!map.value) return false;
  const layers = map.value.getLayers();
  return layers.some((layer) => layer.CLASS_NAME === className);
};

// 移除指定类型的图层
const removeLayerByType = (className) => {
  if (!map.value) return;
  const layers = map.value.getLayers();
  layers.forEach((layer) => {
    if (layer.CLASS_NAME === className) {
      map.value.remove(layer);
    }
  });
};

// 获取地图类型
const getmapTypeClick = (type) => {
  if (type.type == 1) {
    // 标准地图
    if (!hasLayer("AMap.TileLayer")) {
      map.value.add(new AMap.TileLayer());
      // 设置标准地图的 features
      map.value.setFeatures(["bg", "building", "road", "point"]);
    }
  } else {
    // 移除标准地图图层
    if (hasLayer("AMap.TileLayer")) {
      removeLayerByType("AMap.TileLayer");
    }
    // 卫星地图-天地图
    if (!hasLayer("AMap.TileLayer.Satellite")) {
      map.value.add(satelliteLayer.value);
    }
    if (type.road) {
      if (!hasLayer("AMap.TileLayer.RoadNet")) {
        map.value.add(roadNetLayer.value);
      }
    } else {
      if (hasLayer("AMap.TileLayer.RoadNet")) {
        removeLayerByType("AMap.TileLayer.RoadNet");
      }
    }
  }
};

// 显示删除整个面的按钮
const showDeletePolygonButton = (e, clickPoint) => {
  // 如果已经存在删除按钮，先移除
  if (window.currentDeletePolygonButton) {
    removeDeletePolygonButton();
  }

  // 阻止默认右键菜单
  if (e.domEvent) {
    e.domEvent.preventDefault();
    e.domEvent.stopPropagation();
  }

  // 获取点击位置的屏幕坐标
  const pixel = map.value.lngLatToContainer(clickPoint);

  // 创建删除整个面的按钮
  const deletePolygonButton = document.createElement("div");
  deletePolygonButton.className = "delete-polygon-button-container";
  deletePolygonButton.innerHTML = `
    <div class="delete-polygon-tips-marker">
      <p class="delete-polygon-confirm-btn">删除测区</p>
    </div>
  `;
  // 设置删除按钮位置
  deletePolygonButton.style.position = "absolute";
  deletePolygonButton.style.left = pixel.x + 10 + "px";
  deletePolygonButton.style.top = pixel.y - 10 + "px";
  deletePolygonButton.style.zIndex = "1000";

  // 添加到地图容器
  map.value.getContainer().appendChild(deletePolygonButton);

  // 绑定删除按钮事件
  deletePolygonButton.addEventListener("click", () => {
    deleteEntirePolygon();
    removeDeletePolygonButton();
  });

  // 保存删除按钮引用，用于后续移除
  window.currentDeletePolygonButton = deletePolygonButton;

  // 创建地图点击事件处理函数
  // const mapClickHandler = () => {
  //   removeDeletePolygonButton();
  // };

  // 保存事件处理函数引用
  // window.mapClickHandlerForDelete = mapClickHandler;

  // 添加点击其他地方关闭删除按钮的事件
  setTimeout(() => {
    // 监听地图点击事件
    // map.value.on("click", mapClickHandler);

    // 监听文档点击事件
    document.addEventListener("click", closeDeletePolygonButtonOnOutsideClick);
  }, 100);
};

// 移除删除整个面的按钮
const removeDeletePolygonButton = () => {
  if (window.currentDeletePolygonButton) {
    // 移除DOM元素
    window.currentDeletePolygonButton.remove();
    window.currentDeletePolygonButton = null;
  }

  // 移除地图点击事件监听器
  if (map.value && window.mapClickHandlerForDelete) {
    map.value.off("click", window.mapClickHandlerForDelete);
    window.mapClickHandlerForDelete = null;
  }

  // 移除点击其他地方关闭的事件监听器
  document.removeEventListener("click", closeDeletePolygonButtonOnOutsideClick);

  // 清理所有可能的残留引用
  if (window.currentDeletePolygonButton) {
    window.currentDeletePolygonButton = null;
  }
};

// 点击其他地方关闭删除整个面按钮
const closeDeletePolygonButtonOnOutsideClick = (e) => {
  if (
    window.currentDeletePolygonButton &&
    !window.currentDeletePolygonButton.contains(e.target)
  ) {
    removeDeletePolygonButton();
  }
};

// 删除整个多边形
const deleteEntirePolygon = () => {
  try {
    // 移除所有marker
    if (window.markers && window.markers.length > 0) {
      window.markers.forEach((marker) => {
        try {
          map.value.remove(marker);
        } catch (error) { }
      });
      window.markers = [];
    }

    // 移除距离标记和空心小圆点
    if (window.distanceMarkers && window.distanceMarkers.length > 0) {
      window.distanceMarkers.forEach((marker) => {
        try {
          map.value.remove(marker);
        } catch (error) { }
      });
      window.distanceMarkers = [];
    }

    // 移除多边形
    if (window.currentPolygon) {
      try {
        map.value.remove(window.currentPolygon);
        window.currentPolygon = null;
      } catch (error) { }
    }

    // 清空数据
    allData.value = [];

    // 重置状态
    isPolygonFlag.value = false;

    // 重置绘制状态
    if (mouseTool.value) {
      mouseTool.value.close();
    }

    // 清理地图点击事件
    // if (window.mapClickHandler) {
    //   map.value.off("click", window.mapClickHandler);
    //   window.mapClickHandler = null;
    // }

    // 清理鼠标移动事件
    // if (window.mouseDragHandler) {
    //   map.value.off("mousemove", window.mouseDragHandler);
    //   window.mouseDragHandler = null;
    // }

    // 清理mark显示/隐藏事件
    // if (window.visibilityHandler) {
    //   map.value.off("click", window.visibilityHandler);
    //   window.visibilityHandler = null;
    // }

    // 清理右键事件监听器
    // if (window.rightClickHandler) {
    //   map.value.off("rightclick", window.rightClickHandler);
    //   window.rightClickHandler = null;
    // }

    // 重置起飞点
    if (startMarker.value.point && startMarker.value.point.length > 0) {
      startMarker.value.point = [];
    }

    // 清理激光线
    if (window.guideLineLayer) {
      try {
        window.guideLineLayer.setSource(
          new window.Loca.GeoJSONSource({
            data: {
              type: "FeatureCollection",
              features: [],
            },
          })
        );
      } catch (error) { }
    }

    // 发送数据给父组件
    // emit("allData", []);

    // 先清理删除按钮，避免残留
    if (window.currentDeletePolygonButton) {
      removeDeletePolygonButton();
    }
    if (window.currentDeleteButton) {
      removeDeleteButton();
    }

    // 重置全局变量，避免引用已删除的对象
    window.markers = [];
    window.distanceMarkers = [];
    window.currentPolygon = null;
    window.tempPolygon = null;

    // 恢复到绘制状态，允许重新绘制测区
    getmouseDrawClick();

    // 重置绘制状态标志
    isPolygonFlag.value = false;

    // 重置地图光标
    if (map.value) {
      map.value.getContainer().style.cursor = "crosshair";
    }

    ElMessage.success("整个测区已删除，可以重新绘制");
  } catch (error) {
    console.error("删除整个面时出错:", error);
    ElMessage.error("删除整个面失败");
  }
};

// 清理地图资源
const cleanupMap = () => {
  // 清理地图相关资源
  if (map.value) {
    // map.value.clearMap()
    // 清理删除按钮
    if (window.currentDeleteButton) {
      removeDeleteButton();
    }
    // 清理删除整个面按钮
    if (window.currentDeletePolygonButton) {
      removeDeletePolygonButton();
    }

    // 清理地图点击事件监听器
    if (window.mapClickHandler) {
      map.value.off("click", window.mapClickHandler);
      window.mapClickHandler = null;
    }
  }
  if (window.markers) {
    window.markers = '';
  }

  // 清理起飞点点击事件监听
  if (window.takeoffClickHandler && map.value) {
    map.value.off("click", window.takeoffClickHandler);
    window.takeoffClickHandler = null;
  }

  // 清理鼠标移动监听
  if (window.mouseDragHandler && map.value) {
    map.value.off("mousemove", window.mouseDragHandler);
    window.mouseDragHandler = null;
  }

  // 清理mark显示 / 隐藏监听器
  if (window.visibilityHandler && map.value) {
    map.value.off("click", window.visibilityHandler);
    window.visibilityHandler = null;
  }

  // 清理右键事件监听器
  if (window.rightClickHandler && map.value) {
    map.value.off("rightclick", window.rightClickHandler);
    window.rightClickHandler = null;
  }

  if (map.value) {
    // 清理临时多边形
    if (window.tempPolygon) {
      try {
        map.value.remove(window.tempPolygon);
        window.tempPolygon = null;
      } catch (error) { }
    }

    // 清理激光图层
    if (window.currentLaserLayer) {
      try {
        window.currentLaserLayer.destroy();
      } catch (error) { }
      window.currentLaserLayer = null;
    }

    map.value.destroy();
    map.value = null;
  }
};
// 搜索
const getsearchClick = (val) => {
  if (!val) return;
  tipInput.value = val;
  // placeSearch.value.search(tipInput.value, (status, result) => {
  //   if (status === "complete" && result.poiList?.pois) {
  //     address.value = result.poiList.pois;
  //     mapviewRef.value.updateSearchInfo(address.value);
  //     if (address.value.length === 0) {
  //       ElMessage.info("未找到相关地点");
  //     }
  //   } else {
  //     const errorMsg = result?.info || "搜索失败";
  //     ElMessage.error(errorMsg);
  //     console.error("搜索出错:", errorMsg);
  //     address.value = [];
  //   }
  // });
  placeSearch.value.search(tipInput.value, (status, result) => {
    if (status === "complete" && result.poiList?.pois) {
      address.value = result.poiList.pois;
      mapviewRef.value.updateSearchInfo(address.value);
      if (address.value.length === 0) {
        ElMessage.info("未找到相关地点");
      } else {
        handleSearchResults(result.poiList.pois);
      }
    } else {
      const errorMsg = result?.info || "搜索失败";
      ElMessage.error(errorMsg);
      console.error("搜索出错:", errorMsg);
      address.value = [];
    }
  });
};
const handleSearchResults = (pois) => {
  // 清除之前的搜索标记
  clearClick();

  // 遍历并创建新标记
  pois.forEach(poi => {
    // 创建自定义内容，模拟默认样式
    const content = document.createElement('div');
    content.innerHTML = `
      <div style="
        background-color: #FF552E; 
        width: 28px; 
        height: 28px; 
        border: 2px solid white; 
        border-radius: 14px; 
        box-shadow: 0 2px 4px rgba(0,0,0,0.3);
        display: flex;
        align-items: center;
        justify-content: center;
      ">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="white">
          <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5a2.5 2.5 0 0 1 0-5 2.5 2.5 0 0 1 0 5z"/>
        </svg>
      </div>
    `;

    // 创建标记
    const marker = new AMap.Marker({
      position: new AMap.LngLat(poi.location.lng, poi.location.lat), // 标记位置[citation:2]
      content: content, // 使用自定义内容
      offset: new AMap.Pixel(-14, -14), // 偏移，使标记底部中心对准坐标点
      title: poi.name, // 标题[citation:2]
      zIndex: 10,
      map: window.map // 你的地图实例，假设已挂载到window.map
    });
    // 存储标记以便后续管理
    searchMarkers.value.push(marker);
  });
  map.value.add(searchMarkers.value)
}

// 清空搜索出来的点，并且重新绘制面状
const clearClick = () => {
  map.value.remove(searchMarkers.value);
  searchMarkers.value = [];
  // map.value.setFitView();
}
// 选中搜索结果
const getselectItem = (poi) => {
  // 地图中心点
  const markerPosition = [poi.location.lng, poi.location.lat];
  map.value.setCenter(markerPosition);
  map.value.setZoom(16);
};
// 生命周期
onMounted(async () => {
  // 全局阻止右键菜单
  document.addEventListener("contextmenu", (e) => {
    e.preventDefault();
    return false;
  });
  if (route.query.id) {
    isLoadingDefaultRoute.value = true;
    get_airline()
  } else {
    if (window.markers) {
      console.log(window.markers)
      cleanupMap()
    }
    await initMap();
  }
});
const get_airline = async () => {
  isLoadingDefaultRoute.value = false;
  if (window.markers) {
    console.log(window.markers)
    cleanupMap()
  }
  await initMap();
}
onBeforeUnmount(() => {
  // 清理地图
  if (map.value) {
    // 重置鼠标光标样式
    map.value.getContainer().style.cursor = "default";
    map.value.destroy();
  }
});
// 组件卸载时清理
onUnmounted(cleanupMap);

// 添加mark显示/隐藏控制
const addMarkVisibilityControl = () => {
  if (!map.value || !allData.value.length) return;

  // 添加点击事件监听器
  const visibilityHandler = (e) => {
    const clickPoint = e.lnglat;

    // 检查点击点是否在多边形内部
    const isInside = AMap.GeometryUtil.isPointInPolygon(
      clickPoint,
      allData.value
    );

    if (isInside) {
      // 点击图形内部，显示所有mark
      showAllMarks();
    } else {
      // 点击图形外部，隐藏所有mark
      hideAllMarks();
    }
  };

  map.value.on("click", visibilityHandler);
  window.visibilityHandler = visibilityHandler; // 保存引用以便清理
};

// 显示所有mark
const showAllMarks = () => {
  // 显示顶点markers
  if (window.markers && window.markers.length > 0) {
    window.markers.forEach((marker) => {
      if (marker && !marker.getMap()) {
        map.value.add(marker);
      }
    });
  }

  // 显示距离标记和空心小圆点
  if (window.distanceMarkers && window.distanceMarkers.length > 0) {
    window.distanceMarkers.forEach((marker) => {
      if (marker && !marker.getMap()) {
        map.value.add(marker);
      }
    });
  }
};

// 隐藏所有mark
const hideAllMarks = () => {
  // 隐藏顶点markers
  if (window.markers && window.markers.length > 0) {
    window.markers.forEach((marker) => {
      if (marker && marker.getMap()) {
        map.value.remove(marker);
      }
    });
  }

  // 隐藏距离标记和空心小圆点
  if (window.distanceMarkers && window.distanceMarkers.length > 0) {
    window.distanceMarkers.forEach((marker) => {
      if (marker && marker.getMap()) {
        map.value.remove(marker);
      }
    });
  }
};
let set_data_clock = true
const set_data = () => {
  set_data_clock = false
  // 区域
  allData.value = lineform.value.coordinatePointReqList.map(
    (point) => new AMap.LngLat(point.longitude, point.latitude)
  );
  showDefaultRouteMarkers();
  // 起飞点
  // if (lineform.value.takeOffRefPoint) {
  //   let points = lineform.value.takeOffRefPoint.split(',')
  //   // console.log('set_data')
  //   setStartMarker({
  //     lng: points[0],
  //     lat: points[1]
  //   }, false)
  // }
  // 航线
  flightPath_data.flightPath = lineform.value.wayPoints
  set_airline();
  map.value.setFitView()
}
// 将对象数组转换为坐标数组
const convertToCoordinateArray = (objectArray) => {
  return objectArray.map((item) => [item.longitude, item.latitude]);
};

const set_takeOffRefPoint = () => {
  if (lineform.value.takeOffRefPoint) {
    let points = lineform.value.takeOffRefPoint.split(',')
    setTimeout(() => {
      setStartMarker({
        lng: points[0],
        lat: points[1]
      })
    }, 1000);
  }
}
let lineform_setline_clock_t;
watch(() => lineform.value, (a, b) => {
  if (allData.value.length < 3) {
    if (allData.value.length == 0 && lineform.value.coordinatePointReqList.length > 2) {
      // 获取详情赋值
      setTimeout(() => {
        if (set_data_clock) set_data()
      }, 500);
    }
    return
  }
  // console.log('=========')
  let is_refresh = false
  if (a.autoFlightSpeed != lineform_x.autoFlightSpeed || a.direction != lineform_x.direction || a.overlapW != lineform_x.overlapW || a.overlapH != lineform_x.overlapH) {
    is_refresh = true
  } else {
    is_refresh = false
  }
  if (is_refresh) {
    clearTimeout(lineform_setline_clock_t)
    lineform_setline_clock_t = setTimeout(() => {
      get_online_line()
    }, 1000);
  }
  // if (!isNaN(Number(a.height))) {
  //   if (a.height != lineform_x.height) {
  //     setLaserLine(startMarker.value.point)
  //     // set_airline()
  //   }
  // }
  // if (!isNaN(Number(a.takeOffSecurityHeight))) {
  //   if (a.takeOffSecurityHeight != lineform_x.takeOffSecurityHeight) {
  //     setLaserLine(startMarker.value.point)
  //     // set_airline()
  //   }
  // }
  lineform_x = JSON.parse(JSON.stringify(lineform.value))
}, {
  deep: true
})
const setheight = (a, toLine = true) => {
  if (a.height) {
    if (a.height != lineform_x.height) {
      setLaserLine(startMarker.value.point);
    }
  }
  if (a.takeOffSecurityHeight) {
    setLaserLine(startMarker.value.point);
  }
  if (toLine) get_online_line();
  lineform_x = JSON.parse(JSON.stringify(lineform.value))
}
// 暴露方法给父组件使用
defineExpose({
  set_takeOffRefPoint,
  get_online_line,
  enterSetTakeoffMode,
  exitSetTakeoffMode,
  setheight,
});
</script>
